package com.ll.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class RabbitMqConfig {

    @Bean
    public MessageConverter getMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }


    @Autowired
    RabbitTemplate rabbitTemplate;

    //@PostConstruct //本类对象初始化完成之后调用此方法
    public void confirmCallback() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /** 消息到达服务器则会返回ture 否则返回false 利用唯一Id来处理失败的消息
             * @param correlationData 消息的唯一标识 (发送消息时有设置)
             * @param b =true 消息发送到服务器成功
             * @param s 消息发送失败的异常
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                System.out.println("correlationData=>" + correlationData.getId() + "\t\tack=>" + b + "\t\tcause=>" + s);
            }
        });
    }

    //@PostConstruct //本类对象初始化完成之后调用此方法
    public void returnCallback() {
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * @param message 消息本身（头+体）
             * @param replyCode 状态码
             * @param replyText 状态码文本信息
             * @param exchange 该消息发送到那个交换机了
             * @param routingKey 该消息使用的路由键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("message:" + message + "\treplyCode:" + replyCode + "\treplyText:" + replyText + "\texchange:" + exchange + "\troutingKey" + routingKey);
            }
        });
    }

}
